<script setup lang="ts">
import type { ConfigModel } from '#/api/system/models';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, Popconfirm, Tag } from 'ant-design-vue';

import { useVbenVxeGrid, type VxeGridProps } from '#/adapter/vxe-table';
import { deleteConfigApi, getConfigPagedListApi } from '#/api/system/config';

import ConfigFormModal from './form-modal.vue';

defineOptions({ name: 'SystemConfig' });

const gridOptions: VxeGridProps<ConfigModel> = {
  columns: [
    { type: 'seq', width: 60 },
    { field: 'name', title: '配置名称', width: 160 },
    { field: 'code', title: '配置编码', width: 160 },
    { field: 'value', title: '配置值', width: 160 },
    {
      field: 'isFixed',
      title: '内置参数',
      width: 80,
      slots: { default: 'isFixed' },
    },
    { field: 'createdTime', title: '创建时间', minWidth: 160 },
    { field: 'updatedTime', title: '修改时间', minWidth: 160 },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 140,
      slots: { default: 'action' },
    },
  ],
  border: true,
  height: 'auto',
  stripe: true,
  rowConfig: {
    isHover: true,
  },
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await getConfigPagedListApi({
          pageNumber: page.currentPage,
          pageSize: page.pageSize,
        });
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: ConfigFormModal,
});

function openFormModal(row?: ConfigModel) {
  formModalApi.setData({ values: row });
  formModalApi.open();
}

async function deleteHandle(row: ConfigModel) {
  await deleteConfigApi(row.id);
  gridApi.reload();
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <Button type="primary" @click="openFormModal()"> 新增 </Button>
      </template>
      <template #isFixed="{ row }">
        <Tag :color="row.isFixed ? 'green' : 'yellow'">
          {{ row.isFixed ? '是' : '否' }}
        </Tag>
      </template>
      <template #action="{ row }">
        <Button size="small" type="link" @click="openFormModal(row)">
          编辑
        </Button>
        <Popconfirm title="确定要删除吗？" @confirm="deleteHandle(row)">
          <Button size="small" type="link"> 删除 </Button>
        </Popconfirm>
      </template>
    </Grid>
    <FormModal @complete="() => gridApi.reload()" />
  </Page>
</template>
